﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using BUS;
using Public;
using DevExpress.XtraGrid.Views.Grid;
using System.Data.SqlClient;
using System.Data.Odbc;

namespace QuanLyKhoHangVatTu
{
    public partial class frmNhapkho : DevExpress.XtraEditors.XtraForm
    {
        NhapKho_BUS nk_bus = new NhapKho_BUS();
        NhapKho_PB nk_pb = new NhapKho_PB();
        Flag_PB flag_pb = new Flag_PB();

        int SLTon = 0;
        string mahang = "";
        string kho = "";

        public frmNhapkho()
        {
            InitializeComponent();
        }

        private void frmNhapkho_Load(object sender, EventArgs e)
        {
            cboDoiTuong.Properties.DataSource = nk_bus.LayDSNCC();
            cboDoiTuong.Properties.DisplayMember = "MANCC";
            cboDoiTuong.Properties.ValueMember = "TENNCC";

            colMaHang.DataSource = nk_bus.LayDSTonKho();
            colMaHang.DisplayMember = "MAVATTU";
            colMaHang.ValueMember = "MAVATTU";

            colKho.DataSource = nk_bus.LayDSKho();
            colKho.DisplayMember = "TENKHO";
            colKho.ValueMember = "MAKHO";


            DataTable dt = nk_bus.LayDSCTNhapKho();
            gridControl1.DataSource = dt;


            if (Flag_PB.ThemSua == 1)
            {
                txtMa.ResetText();
                cboDoiTuong.ResetText();
                txtTenDoiTuong.ResetText();
                txtNguoiGiaoHang.ResetText();
                txtDienGiai.ResetText();
                dtHachToan.ResetText();
                dtChungTu.ResetText();
                txtMa.ResetText();
                try
                {
                    txtMa.Text = nk_bus.NextID_PN();
                }
                catch
                {
                    txtMa.Text = "PN0001";
                }

                EnableEditing(false);
            }
            if (Flag_PB.ThemSua == 2)
            {
                txtMa.Text = NhapKho_PB.MaPhieuNhap;
                cboDoiTuong.SelectedText= NhapKho_PB.MaNCC;
                txtTenDoiTuong.Text = NhapKho_PB.TenNCC;
                txtNguoiGiaoHang.Text = NhapKho_PB.NguoiGiaoHang;
                txtDienGiai.Text = NhapKho_PB.DienGiai;
                dtHachToan.EditValue= NhapKho_PB.NgayHachToan;
                dtChungTu.EditValue = NhapKho_PB.NgayChungTu;
                gridControl1.DataSource = nk_bus.TimMaPhieuNhap(txtMa.Text);

                EnableEditing(false);
                menuXoa.Enabled = true;

                this.gridView1.NewItemRowText = "Sửa chi tiết nhập kho";
                this.gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;

                DataRowView row1 = gridView1.GetFocusedRow() as DataRowView;
                if (row1 == null) return;

                SLTon= Int32.Parse( row1["SOLUONG"].ToString());
                mahang = row1["MAHANG"].ToString();
                kho = row1["MAKHO"].ToString();
                
            }

            
            
        }

        #region "Enable Controls"
        private void EnableEditing(bool editing)
        {
            menuThem.Enabled = editing;
            menuSua.Enabled = editing;
            menuXoa.Enabled = editing;
            menuLuu.Enabled = !editing;
            menuHoan.Enabled = !editing;
            menuDong.Enabled = !editing;
        }

        private void EnableTextBox(bool editing)
        {
            txtMa.Enabled = editing;
            cboDoiTuong.Enabled = editing;
            txtTenDoiTuong.Enabled = editing;
            txtNguoiGiaoHang.Enabled = editing;
            txtDienGiai.Enabled = editing;
            dtChungTu.Enabled = editing;
            dtHachToan.Enabled = editing;
            txtMa.Enabled = editing;
            gridControl1.Enabled = editing;
        }
        #endregion

        #region"Kiểm tra rỗng"
        private bool CheckNull()
        {
            if (txtMa.Text == "" || cboDoiTuong.Text == "" || txtTenDoiTuong.Text == "" || txtNguoiGiaoHang.Text == "" || dtChungTu.Text == "" || dtHachToan.Text == "")
            {
                return false;
            }
            return true;
        }
        #endregion

        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        private void barButtonItem1_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void xtraTabPage1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }

        private void gridControl1_Click_1(object sender, EventArgs e)
        {

        }

        private void textEdit1_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void cboDoiTuong_EditValueChanged(object sender, EventArgs e)
        {
            txtTenDoiTuong.Text = cboDoiTuong.EditValue.ToString();
            
        }

        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (gridView1.DataRowCount > 0)
            {
                for (int i = gridView1.RowCount - 1; i >= 0; i--)
                {
                    NhapKho_PB.MaHang = gridView1.GetRowCellValue(i, "MAHANG").ToString();
                    NhapKho_PB.MaKho = gridView1.GetRowCellValue(i, "MAKHO").ToString();
                    NhapKho_PB.SoLuong = gridView1.GetRowCellValue(i, "SOLUONG").ToString();
                    NhapKho_PB.ThanhTien = Convert.ToDecimal(gridView1.GetRowCellValue(i, "THANHTIEN").ToString());
                    NhapKho_PB.DonGia = Convert.ToDecimal(gridView1.GetRowCellValue(i, "DONGIA").ToString());

                    if (NhapKho_PB.MaHang == "" || NhapKho_PB.MaKho == "" || NhapKho_PB.SoLuong == "" || NhapKho_PB.ThanhTien.ToString() == "" || NhapKho_PB.DonGia.ToString() == "")
                    {
                        MessageBox.Show("Vui lòng điền đầy đủ thông tin Chi tiết nhập kho", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }
                if (CheckNull())
                {
                    if (Flag_PB.ThemSua == 1)
                    {
                        GetValues();
                        nk_bus.ThemNhapKho(nk_pb);
                        for (int i = gridView1.RowCount - 1; i >= 0; i--)
                        {
                            try
                            {
                                NhapKho_PB.ID = nk_bus.NextID_CTN();
                            }
                            catch
                            {
                                NhapKho_PB.ID = "CTN0001";
                            }
                            NhapKho_PB.MaHang = gridView1.GetRowCellValue(i, "MAHANG").ToString();
                            NhapKho_PB.MaKho = gridView1.GetRowCellValue(i, "MAKHO").ToString();
                            NhapKho_PB.SoLuong = gridView1.GetRowCellValue(i, "SOLUONG").ToString();
                            NhapKho_PB.ThanhTien = Convert.ToDecimal(gridView1.GetRowCellValue(i, "THANHTIEN").ToString());
                            NhapKho_PB.DonGia = Convert.ToDecimal(gridView1.GetRowCellValue(i, "DONGIA").ToString());
                            nk_bus.ThemCTNhapKho(nk_pb);
                            if (nk_bus.CheckExists(NhapKho_PB.MaHang,NhapKho_PB.MaKho))
                            {
                                int sl = nk_bus.LaySLTonKho(NhapKho_PB.MaHang, NhapKho_PB.MaKho);
                                sl += Int32.Parse(NhapKho_PB.SoLuong);
                                NhapKho_PB.SoLuong = sl.ToString();
                                nk_bus.SuaTonKho(nk_pb);
                            }
                            else
                            {
                                try
                                {
                                   NhapKho_PB.IDTonKho=nk_bus.NextID_TK();
                                }
                                catch
                                {
                                    NhapKho_PB.IDTonKho="TK0001";
                                    
                                }
                                nk_bus.ThemTonKho(nk_pb);
                            }
                        }
                    }
                    if (Flag_PB.ThemSua == 2)
                    {
                        GetValues();
                        nk_bus.SuaNhapKho(nk_pb);
                        for (int i = gridView1.RowCount - 1; i >= 0; i--)
                        {
                            NhapKho_PB.MaHang = gridView1.GetRowCellValue(i, "MAHANG").ToString();
                            NhapKho_PB.MaKho = gridView1.GetRowCellValue(i, "MAKHO").ToString();
                            NhapKho_PB.SoLuong = gridView1.GetRowCellValue(i, "SOLUONG").ToString();
                            NhapKho_PB.ThanhTien = Convert.ToDecimal(gridView1.GetRowCellValue(i, "THANHTIEN").ToString());
                            NhapKho_PB.DonGia = Convert.ToDecimal(gridView1.GetRowCellValue(i, "DONGIA").ToString());
                            NhapKho_PB.ID = gridView1.GetRowCellValue(i, "ID").ToString();
                            nk_bus.SuaCTNhapKho(nk_pb);
                            if (nk_bus.CheckExists(NhapKho_PB.MaHang, NhapKho_PB.MaKho))
                            {
                                if (mahang != NhapKho_PB.MaHang || kho != NhapKho_PB.MaKho)
                                {
                                    int sl = nk_bus.LaySLTonKho(NhapKho_PB.MaHang, NhapKho_PB.MaKho);
                                    sl += Int32.Parse(NhapKho_PB.SoLuong);
                                    NhapKho_PB.SoLuong = sl.ToString();
                                    nk_bus.SuaTonKho(nk_pb);
                                    NhapKho_PB.SoLuong = gridView1.GetRowCellValue(i, "SOLUONG").ToString();
                                    int sl1 = nk_bus.LaySLTonKho(mahang, kho);
                                    sl1 -= SLTon;
                                    NhapKho_PB.SoLuong = sl1.ToString();
                                    NhapKho_PB.MaHang = mahang;
                                    NhapKho_PB.MaKho = kho;
                                    nk_bus.SuaTonKho(nk_pb);
                                }
                                else
                                {
                                    NhapKho_PB.MaHang = gridView1.GetRowCellValue(i, "MAHANG").ToString();
                                    NhapKho_PB.MaKho = gridView1.GetRowCellValue(i, "MAKHO").ToString();
                                    if (SLTon > Int32.Parse(NhapKho_PB.SoLuong))
                                    {
                                        NhapKho_PB.SoLuong = gridView1.GetRowCellValue(i, "SOLUONG").ToString();
                                        SLTon -= Int32.Parse(NhapKho_PB.SoLuong);
                                        int sl = nk_bus.LaySLTonKho(NhapKho_PB.MaHang, NhapKho_PB.MaKho);
                                        sl -= SLTon;
                                        NhapKho_PB.SoLuong = sl.ToString();
                                        nk_bus.SuaTonKho(nk_pb);
                                    }
                                    else
                                    {
                                        NhapKho_PB.SoLuong = gridView1.GetRowCellValue(i, "SOLUONG").ToString();
                                        int a = Int32.Parse(NhapKho_PB.SoLuong);
                                        a -= SLTon;
                                        int sl = nk_bus.LaySLTonKho(NhapKho_PB.MaHang, NhapKho_PB.MaKho);
                                        sl += a;
                                        NhapKho_PB.SoLuong = sl.ToString();
                                        nk_bus.SuaTonKho(nk_pb);
                                    }
                                }

                            }
                            else
                            {
                                NhapKho_PB.IDTonKho = nk_bus.NextID_TK();
                                if (mahang != NhapKho_PB.MaHang || kho != NhapKho_PB.MaKho)
                                {
                                    nk_bus.ThemTonKho(nk_pb);
                                    NhapKho_PB.SoLuong = gridView1.GetRowCellValue(i, "SOLUONG").ToString();
                                    int sl1 = nk_bus.LaySLTonKho(mahang, kho);
                                    sl1 -= SLTon;
                                    NhapKho_PB.SoLuong = sl1.ToString();
                                    NhapKho_PB.MaHang = mahang;
                                    NhapKho_PB.MaKho = kho;
                                    nk_bus.SuaTonKho(nk_pb);
                                }
                                else
                                    nk_bus.ThemTonKho(nk_pb);
                            }
                        }
                    }
                    menuThem.Enabled = true;
                    menuSua.Enabled = false;
                    menuXoa.Enabled = false;
                    menuLuu.Enabled = false;
                    menuHoan.Enabled = false;
                    menuDong.Enabled = true;
                    EnableTextBox(false);
                }
                else
                {
                    MessageBox.Show("Vui lòng điền đầy đủ thông tin Phiếu nhập", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            else
            {
                MessageBox.Show("Vui lòng điền đầy đủ thông tin Chi tiết nhập kho", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }
        #region "Lấy giá trị textbox"
        private NhapKho_PB GetValues()
        {
            NhapKho_PB.MaPhieuNhap = txtMa.Text;
            NhapKho_PB.MaNCC = cboDoiTuong.Text;
            NhapKho_PB.NguoiGiaoHang = txtNguoiGiaoHang.Text;
            NhapKho_PB.DienGiai = txtDienGiai.Text;
            NhapKho_PB.NgayHachToan = Convert.ToDateTime(dtHachToan.EditValue);
            NhapKho_PB.NgayChungTu = Convert.ToDateTime(dtChungTu.EditValue);
            return nk_pb;
        }
        #endregion

        private void menuThem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Flag_PB.ThemSua = 1;
            EnableTextBox(true);
            txtMa.ResetText();
            txtNguoiGiaoHang.ResetText();
            txtDienGiai.ResetText();
            dtHachToan.ResetText();
            dtChungTu.ResetText();
            txtMa.ResetText();
            txtMa.Text = nk_bus.NextID_PN();

            EnableEditing(false);
            gridControl1.DataSource = nk_bus.LayDSCTNhapKho();

            this.gridView1.NewItemRowText = "Click để thêm 1 dòng mới";
            this.gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.True;


        }

        private void dateEdit2_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void txtNguoiGiaoHang_TextChanged(object sender, EventArgs e)
        {

        }

        private void gridView1_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            // Sự kiện này để người ta không chuyển qua dòng khác được khi có lỗi xảy ra nè
            // Nó nhận giá trị e.Valid của gridView1_ValidateRow để ứng xử
            // neu e,Valid =True thì nó cho chuyển qua dòng khác hoặc làm tác vụ khác
            // và ngược lại
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            //if (Flag_PB.ThemSua == 2)
            //{
            //    NhapKho_PB.ID = nk_bus.NextID_CTN();
            //    NhapKho_PB.MaPhieuNhap = txtMa.Text;
            //    NhapKho_PB.MaHang = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "MAHANG").ToString();
            //    NhapKho_PB.MaKho = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "MAKHO").ToString();
            //    NhapKho_PB.SoLuong = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "SOLUONG").ToString();
            //    NhapKho_PB.ThanhTien = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "THANHTIEN").ToString();
            //    NhapKho_PB.DonGia = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "DONGIA").ToString();
            //    ////Kiểm tra đây là dòng dữ liệu mới hay cũ, nếu là mới thì mình insert
            //    GridView view = sender as GridView;
            //    if (view.IsNewItemRow(e.RowHandle))
            //        nk_bus.ThemCTNhapKho(nk_pb);
            //}
            ////ngược lại thì update
            //else
            //{
            //    NhapKho_PB.ID = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID").ToString();
            //    nk_bus.SuaCTNhapKho(nk_pb);

            //}
            //frmNhapkho_Load(sender, e);
        }

        private void gridControl1_Click_2(object sender, EventArgs e)
        {

        }

        private void menuXoa_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            menuHoan.Enabled = false;

            if (MessageBox.Show("Bạn có thực sự muốn xóa (những) dòng đã chọn không?","Thông báo",MessageBoxButtons.YesNo,MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                for (int i = gridView1.GetSelectedRows().Length - 1; i >= 0; i--)
                {
                    NhapKho_PB.ID = gridView1.GetRowCellValue(gridView1.GetSelectedRows()[i], "ID").ToString();
                    nk_bus.XoaCTNhapKho(nk_pb);
                }
                gridControl1.DataSource = nk_bus.TimID(nk_pb);
            }
        }

        private void menuDong_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DialogResult = DialogResult.OK;
            this.Close();
        }

        private void xtraTabControl1_Click(object sender, EventArgs e)
        {

        }

        private void gridView1_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            DataRowView row = gridView1.GetFocusedRow() as DataRowView;
            if (row == null) return;

            row["SOLUONG"] = 1;
            row["DONGIA"] = 0;
        }

        private void colMaHang_EditValueChanged(object sender, EventArgs e)
        {
            var lkpMaHang = sender as LookUpEdit;
            if (lkpMaHang == null) return;

            DataRow row = gridView1.GetFocusedDataRow();
            if (row == null) return;

            // tim ten hang rồi gán cho row["tenhang"]
            DataTable dtVattu = lkpMaHang.Properties.DataSource as DataTable;
            if (dtVattu == null) return;

            dtVattu.PrimaryKey = new DataColumn[] { dtVattu.Columns["MAVATTU"] };
            DataRow vattu = dtVattu.Rows.Find(lkpMaHang.EditValue);
            if (vattu == null) return;

            row["TENVATTU"] = vattu["TENVATTU"];
            row["DIENGIAI"]=vattu["DIENGIAI"];
            row["DONGIA"] = vattu["DONGIAMUA"];
        }

        private void txtMa_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            DataRow chiTiet = gridView1.GetFocusedDataRow();
            if (chiTiet == null) return;

            chiTiet["THANHTIEN"] = Convert.ToDecimal(chiTiet["SOLUONG"]) * Convert.ToDecimal(chiTiet["DONGIA"]);



            //if (e.Column.Name == "colSoLuong" || e.Column.Name == "colDonGia")
            //{
            //    if (gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "colSoLuong").ToString() != null && gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "colDonGia").ToString() != null)
            //    {
            //        double SoLuong = Convert.ToDouble(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "colSoLuong").ToString());
            //        double DonGia = Convert.ToDouble(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "colDonGia").ToString());
            //        double ThanhTien = SoLuong * DonGia;
            //        gridView1.SetFocusedRowCellValue("colThanhTien", ThanhTien.ToString());
            //    }
            //}
            //else
            //{
            //    return;
            //}
            //if (e.Column.Name == "colSoLuong" || e.Column.Name == "colDonGia")
            //{
            //    DataTable dt = gridControl1.DataSource as DataTable;
            //    dt.Columns["colThanhTien"].Expression = "SOLUONG*THANHTIEN";
            //}
        }

            
        }
    }